package com.rentong.cust.controller;

import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.rentong.common.core.page.PageDomain;
import com.rentong.common.core.page.TableSupport;
import com.rentong.cust.mapper.CustMaintenanceMapper;
import com.rentong.cust.utils.PageByList;
import com.rentong.cust.vo.CustMaintenanceDto;
import com.rentong.cust.vo.ExportExcel;
import com.rentong.cust.vo.ExportExcelDto;
import com.rentong.cust.vo.MaintenanceVo;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.rentong.common.annotation.Log;
import com.rentong.common.core.controller.BaseController;
import com.rentong.common.core.domain.AjaxResult;
import com.rentong.common.enums.BusinessType;
import com.rentong.cust.domain.CustMaintenance;
import com.rentong.cust.service.ICustMaintenanceService;
import com.rentong.common.utils.poi.ExcelUtil;
import com.rentong.common.core.page.TableDataInfo;

/**
 * 维修表列表Controller
 *
 * @author ruoyi
 * @date 2024-12-30
 */
@RestController
@RequestMapping("/maintenance/maintenance")
public class CustMaintenanceController extends BaseController {
    @Autowired
    private ICustMaintenanceService custMaintenanceService;

    @Autowired
    private CustMaintenanceMapper custMaintenanceMapper;

    /**
     * 查询维修表列表列表
     */
//    //('maintenance:maintenance:list')")
    @GetMapping("/list")
    public TableDataInfo list(CustMaintenanceDto custMaintenance) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        List<MaintenanceVo> list = custMaintenanceService.selectCustMaintenanceList(custMaintenance);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(PageByList.startPage(list, pageNum, pageSize));
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;

    }

//    /**
//     * 导出维修表列表列表
//     */
//    //('maintenance:maintenance:export')")
//    @Log(title = "维修表列表", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, @RequestParam String maintenanceIds) throws IOException {
//        custMaintenanceService.exportUsingTemplate(maintenanceIds);
//    }


    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void exportUsingTemplate(@RequestParam String maintenanceIds, HttpServletResponse response) throws IOException {
        if (!StringUtil.isEmpty(maintenanceIds)) {
            String[] split = maintenanceIds.split(",");
            List<ExportExcelDto> exportExcelDtos = new ArrayList<>();
            for (String s : split) {
                exportExcelDtos.add(custMaintenanceMapper.export(Integer.parseInt(s)));
            }
            boolean flag = hasDifferentRegionId(exportExcelDtos);
            if (flag) {
                return;
            }
            List<ExportExcel> list = new ArrayList<>();
            for (ExportExcelDto exportExcelDto : exportExcelDtos) {
                ExportExcel exportExcel = new ExportExcel();
                exportExcel.setEventDescription(exportExcelDto.getEventDescription());
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M月d日");
                exportExcel.setMaintenanceTime(exportExcelDto.getMaintenanceTime().format(formatter));
                exportExcel.setV3("");
                exportExcel.setV4("");
                exportExcel.setV5("");
                exportExcel.setV6("");
                list.add(exportExcel);
                if (!CollectionUtils.isEmpty(exportExcelDto.getCustMaintenanceListName())) {
                    for (String name : exportExcelDto.getCustMaintenanceListName()) {
                        ExportExcel exportExcel2 = new ExportExcel();
                        exportExcel2.setMaintenanceTime("");
                        exportExcel2.setEventDescription(name);
                        exportExcel2.setV3("");
                        exportExcel2.setV4("");
                        exportExcel2.setV5("");
                        exportExcel2.setV6("");
                        list.add(exportExcel2);
                    }
                }
            }

            // 加载模板文件（放在 src/main/resources/templates/2.xlsx 中）
            InputStream templateFileInputStream = getClass().getClassLoader().getResourceAsStream("templates/2.xlsx");

            if (templateFileInputStream == null) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("模板文件未找到");
                return;
            }

            // 创建 ExcelWriter 实例
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ExcelWriter writer = EasyExcel
                    .write(byteArrayOutputStream)
                    .withTemplate(templateFileInputStream)
                    .build();

            WriteSheet sheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder()
                    .forceNewRow(true)
                    .build();
            writer.fill(list, fillConfig, sheet);
            writer.finish();

            // 设置文件响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("maintenance_data.xlsx", "UTF-8"));
            response.setContentLength(byteArrayOutputStream.size());

            // 将文件写入响应流
            try (OutputStream out = response.getOutputStream()) {
                byteArrayOutputStream.writeTo(out);
            } catch (IOException e) {
                e.printStackTrace();
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }
    }

    public boolean hasDifferentRegionId(List<ExportExcelDto> exportExcelDtos) {
        Set<Integer> regionIds = new HashSet<>();  // 使用 Set 来去重 regionId

        for (ExportExcelDto dto : exportExcelDtos) {
            regionIds.add(dto.getRegionId());
            if (regionIds.size() > 1) {
                return true;  // 返回 true 表示有不相同的 regionId
            }
        }

        return false;  // 如果所有 regionId 都相同，返回 false
    }


    /**
     * 获取维修表列表详细信息
     */
//    //('maintenance:maintenance:query')")
    @GetMapping(value = "/{maintenanceId}")
    public AjaxResult getInfo(@PathVariable("maintenanceId") Long maintenanceId) {
        return success(custMaintenanceService.selectCustMaintenanceByMaintenanceId(maintenanceId));
    }

    /**
     * 新增维修表列表
     */
  //  //('maintenance:maintenance:add')")
    @Log(title = "维修表列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CustMaintenance custMaintenance) {
        return toAjax(custMaintenanceService.insertCustMaintenance(custMaintenance));
    }

    /**
     * 修改维修表列表
     */
   // //('maintenance:maintenance:edit')")
    @Log(title = "维修表列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MaintenanceVo maintenanceVo) {
        CustMaintenance custMaintenance = new CustMaintenance();
        BeanUtils.copyProperties(maintenanceVo, custMaintenance);
        custMaintenance.setUpdateTime(new Date());
        return toAjax(custMaintenanceService.updateCustMaintenance(custMaintenance));
    }

    /**
     * 删除维修表列表
     */
   // //('maintenance:maintenance:remove')")
    @Log(title = "维修表列表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{maintenanceIds}")
    public AjaxResult remove(@PathVariable Long[] maintenanceIds) {
        return toAjax(custMaintenanceService.deleteCustMaintenanceByMaintenanceIds(maintenanceIds));
    }


}
